package com.legleg.util;

import com.legleg.data.Album;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlParserUtil {
    public static SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static HtmlParserUtil parserutil = new HtmlParserUtil();
    private static HttpClient client = new DefaultHttpClient();
    private HtmlCleaner cleaner = null;

    public HtmlParserUtil() {
        cleaner = new HtmlCleaner();
    }

    public static HtmlParserUtil getInstance() {
        synchronized (parserutil) {
            if (parserutil == null) {
                parserutil = new HtmlParserUtil();
            }
        }

        return parserutil;

    }

    static {
        HttpParams params = new BasicHttpParams();
        ConnManagerParams.setMaxTotalConnections(params, 100);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

        // Create and initialize scheme registry
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        client = new DefaultHttpClient(cm, params);
        client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    }


    //get tag property value
    public String parseAttrByTag(String content, String attrName, String attrValue, String attrProperty) {
        String res = "";
        TagNode tag = cleaner.clean(content);

        try {

            Object[] obj = tag.getElementsByAttValue(attrName, attrValue, true, true);
            if (obj.length > 0) {
                res = ((TagNode) obj[0]).getAttributeByName(attrProperty);

            }

        } catch (Exception e) {
            System.out.println("******parser tag error***********");
            e.printStackTrace();
        }

        return res;
    }


    //
    public String parseAttrByTag(String content, String tagName, String attrName) {
        String res = "";
        TagNode tag = cleaner.clean(content);

        try {

            Object[] obj = tag.getElementsByName(tagName, true);
            if (obj.length > 0) {
                res = ((TagNode) obj[0]).getAttributeByName(attrName);

            }

        } catch (Exception e) {
            System.out.println("******parser tag error***********");
            e.printStackTrace();
        }

        return res;
    }

    public List<String> parseAttrListByXpath(String content, String evluatePath, String attrName) {
        List<String> ret = null;
        TagNode tag = cleaner.clean(content);

        try {
            Object[] obj = tag.evaluateXPath(evluatePath);
            if (obj.length > 0) {
                ret = new ArrayList<String>();
                for (Object o : obj) {
                    ret.add(((TagNode) o).getAttributeByName(attrName));
                }
            }

        } catch (Exception e) {
            System.out.println("******parser tag error***********");
            e.printStackTrace();
        }

        return ret;
    }

    public List<String> parseTextListByXpath(String content, String evluatePath) {
        List<String> ret = null;
        TagNode tag = cleaner.clean(content);
        try {
            Object[] obj = tag.evaluateXPath(evluatePath);
            if (obj.length > 0) {
                ret = new ArrayList<String>();
                for (Object o : obj) {
                    ret.add(((TagNode) o).getText().toString());
                }
            }

        } catch (Exception e) {
            System.out.println("******parser tag error***********");
            e.printStackTrace();
        }
        return ret;
    }


    //get tag text
    public String parseTextByTag(String content, String evluatePath) {
        String res = "";
        TagNode tag = cleaner.clean(content);

        try {

            Object[] obj = tag.evaluateXPath(evluatePath);
            if (obj.length > 0) {
                StringBuffer sb = ((TagNode) obj[0]).getText();
                if (sb != null)
                    res = sb.toString();
            }

        } catch (Exception e) {
            System.out.println("******parser tag error***********");
            e.printStackTrace();
        }
        return res;
    }


    public List<Album> parseLinks(String content, String evluatePath) {
        ArrayList<Album> list = null;

        TagNode tag = cleaner.clean(content);

        try {
            Object[] obj = tag.evaluateXPath(evluatePath);

            if (obj != null && obj.length > 0) {
                list = new ArrayList<Album>();
                for (Object node : obj) {
                    String link = ((TagNode) node).getAttributeByName("href");
                    if (link != null && link.length() > 0) {
                        Album album = new Album();
                        album.setPageurl(link);
                        list.add(album);
                    }
                }
                System.out.println("html list link resuts :   " + obj.length);
            }
        } catch (XPatherException e) {
            e.printStackTrace();
        }
        return list;
    }

/*	public ArrayList<MediaEntry> parseLinkTag(String site,String content,String evluatePath) {
		ArrayList<MediaEntry> list=new ArrayList<MediaEntry>();
	
		TagNode tag=cleaner.clean(content);
	
		try {
			Object[] obj=tag.evaluateXPath(evluatePath);
		
			if(obj!=null && obj.length>0){
				for(Object node:obj){
					MediaEntry me=new MediaEntry();
					String link=((TagNode)node).getAttributeByName("href");	
					if(link!=null && link.length()>0)
						if(!link.toLowerCase().contains(site)){
							link=site+link;	
							if(!link.contains("http://"))
								link="http://"+link;
						}
					    
						me.pageurl=link;
						list.add(me);	
				}
				System.out.println("html list link resuts :   "+obj.length);
			}
		} catch (XPatherException e) {
			e.printStackTrace();
		}
		return list;
	
	}
	
	public ArrayList<MediaEntry> parseTagurl(String site,String content,String evluatePath,String attr) {
		ArrayList<MediaEntry> list=new ArrayList<MediaEntry>();
	
		TagNode tag=cleaner.clean(content);
	
		try {
			Object[] obj=tag.evaluateXPath(evluatePath);
		
			if(obj!=null && obj.length>0){
				for(Object node:obj){
					MediaEntry me=new MediaEntry();
					String link=((TagNode)node).getAttributeByName(attr);	
					if(link!=null && link.length()>0)
						if(!link.toLowerCase().contains(site)){
							link=site+link;	
							if(!link.contains("http://"))
								link="http://"+link;
						}
					    
						me.pageurl=link;
						list.add(me);	
				}
				System.out.println("html list link resuts :   "+obj.length);
			}
		} catch (XPatherException e) {
			e.printStackTrace();
		}
		return list;
	
	}*/


    public String parseTagOfAttr(String content, String evluatePath, String attr) {
        String res = "";
        TagNode tag = cleaner.clean(content);

        try {
            Object[] obj = tag.evaluateXPath(evluatePath);

            if (obj != null && obj.length > 0) {

                res = ((TagNode) obj[0]).getAttributeByName(attr);

            }
        } catch (XPatherException e) {
            e.printStackTrace();
        }
        return res;

    }


    public static String patternStr(String content, String regex) {
        String res = "";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        if (m.find()) {
            if (m.group() != null)
                res = m.group(1);
        }

        return res;
    }


    public static String getHtml(String url, String[][] headers) {
        HttpGet httpGet = null;
        String ret = "";
        try {
            httpGet = new HttpGet();
            httpGet.setURI(new URI(url));
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
        if (httpGet.getAllHeaders() == null) {
            httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0");
            httpGet.addHeader("Keep-Alive", "115");
            httpGet.addHeader("Connection", "Keep-Alive");
            httpGet.addHeader("Accept-Encoding", "gzip,deflate");
            httpGet.addHeader("Content-Type", "text/html;charset=utf-8");
            httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

            if (headers != null) {
                for (int i = 0; i < headers.length; i++) {
                    if (headers[i] != null) {
                        httpGet.addHeader(headers[i][0], headers[i][1]);
                        //System.out.println("setting "+headers[i][0]+": "+headers[i][1]);
                    }
                }
            }
        }


        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            ret = client.execute(httpGet, responseHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;


    }

}
